package com.luoling.readExcel;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

/**
 * Description:
 * Copyright:   Copyright (c)2024
 * Company:
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2024-07-16 16:39:17
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2024-07-16     张李鑫                     1.0         1.0 Version
 */
public class DbUtils {
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static String toJson(ResultSet resultSet) throws Exception {

        ArrayNode jsonArray = objectMapper.createArrayNode();

        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        while (resultSet.next()) {
            ObjectNode obj = objectMapper.createObjectNode();

            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnName(i);
                String value = resultSet.getString(i);
                obj.put(columnName, value);
            }

            jsonArray.add(obj);
        }

        return objectMapper.writeValueAsString(jsonArray);
    }


    public static SqlSessionFactory readMybatisConfig(String resource) throws Exception {
        // 3. 使用 SqlSessionFactoryBuilder 加载配置文件和数据源，创建 SqlSessionFactory
        return new SqlSessionFactoryBuilder().build(Files.newInputStream(Paths.get(System.getProperty("user.dir") + File.separator + resource)));
    }
}
